package com.xiongmao.webflux.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiongmao.webflux.auth.entity.vo.SysUserVo;
import com.xiongmao.webflux.auth.service.AuthService;
import com.xiongmao.webflux.common.CommonConst;
import com.xiongmao.webflux.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Stream;

/**
 * @Author: lao_hu
 * @Date: 2022/2/25 15:36
 * @Description:
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisUtils redisUtils;

    //服务鉴权
    @Override
    public boolean permission(String sid, String url) {
        boolean flag = false;
        //根据sid获取用户信息，并更新sid存活时间
        String userInfo = redisUtils.get(CommonConst.SESSION_CACHE + sid);
        if (null != userInfo){
            SysUserVo vo = JSON.parseObject(userInfo,SysUserVo.class);
            //这里根据请求的url进行的鉴权，也可以根据角色id等进行鉴权
            Set<String> permissions = vo.getPermissions();
            Set<Integer> roles = vo.getRoles();
            flag = permissions.contains(url);
            //TODO 从认证服务获取是否有权限,远程调用
            flag = true;
            return flag;
        }else {
            // 这里正常肯定可以获取用户、权限信息，若取不到直接返回 false
            return flag;
        }
    }

    @Override
    public boolean isExitAndFrash(String sid) {
        //调用前，判断存在并刷新key存活时间
        return redisUtils.hasKey(CommonConst.SESSION_CACHE + sid,CommonConst.DEFAULT_EXPIRE);
    }
}
